package com.company.排序.冒泡排序;

import java.util.Arrays;

/**
 * @author uguoy089
 * @Description:
 * @Date: 2021/5/10 14:33
 */

public class Sort3 {

    public static void sort(int[] array) {
        int temp;
        //记录最后一次交换的位置
        int lastExchangeIndex = 0;
        //无序数列的边界，每次比较只需要比到这里为止
        int sortBorder = array.length - 1;
        for (int i = 0; i < array.length; i++) {
            //有序标记，每一轮的初始是true
            boolean flag = true;
            for (int j = 0; j < sortBorder; j++) {
                if (array[j] > array[j + 1]) {
                    temp = array[j + 1];
                    array[j + 1] = array[j];
                    array[j] = temp;
                    //有元素交换，所以不是有序，标记变为false
                    flag = false;
                    //把无序数列的边界更新为最后一次交换元素的位置
                    lastExchangeIndex = j;
                }
            }
            sortBorder = lastExchangeIndex;
            if (flag) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] array = new int[]{5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 75, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 75, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7,
                5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 75, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7,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 8, 6, 3, 9, 2, 1, 75, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 75, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7,
                5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 75, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 75, 8, 6, 3, 9, 2, 1, 7, 5, 8, 6, 3, 9, 2, 1, 7};
        long startTime = System.currentTimeMillis();
        sort(array);
        long endTime = System.currentTimeMillis();
        System.out.println("time3 = " + (endTime-startTime));
        System.out.println(Arrays.toString(array));
    }
}
